package com.guit.hrms.websocket;

import com.guit.hrms.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MessageWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private TokenService tokenService;

    // 存储WebSocketSession的映射表，键为用户ID
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

//    public void setTokenService(TokenService service) {
//        this.tokenService = service;
//    }

    // 当WebSocket连接建立后，将session与用户ID关联并存储
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            // 从URL参数中提取token和employeeId
            String queryString = Objects.requireNonNull(session.getUri()).getQuery();
            String token = extractParameter(queryString, "token");
            String employeeId = extractParameter(queryString, "employeeId");

            // 验证token
            if (token != null && employeeId != null && tokenService.validateToken(employeeId, token)) {
                sessions.put(employeeId, session);
            } else {
                // token无效，关闭连接
                session.close(CloseStatus.POLICY_VIOLATION.withReason("认证失败"));
            }
        } catch (Exception e) {
            session.close(CloseStatus.SERVER_ERROR.withReason("服务器错误"));
        }
    }

    // 处理接收到的文本消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理从客户端接收的消息
        String payload = message.getPayload();
        // 处理逻辑... 暂无
    }

    // 当WebSocket连接关闭后，移除用户ID与session的关联
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String employeeId = extractParameter(Objects.requireNonNull(session.getUri()).getQuery(), "employeeId");
        sessions.remove(employeeId);
    }

    // 从WebSocketSession中提取用户ID
    // 从查询字符串中提取参数
    private String extractParameter(String queryString, String paramName) {
        if (queryString == null) return null;

        String[] params = queryString.split("&");
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length == 2 && keyValue[0].equals(paramName)) {
                return keyValue[1];
            }
        }
        return null;
    }

    // 发送消息给指定用户
    public static void sendToUser(String employeeId, String message) {
        WebSocketSession session = sessions.get(employeeId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                sessions.remove(employeeId);
            }
        }
    }

    // 广播消息给所有在线用户
    public static void broadcast(String message) {
        sessions.forEach((employeeId, session) -> {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    sessions.remove(employeeId);
                }
            }
        });
    }
}
